import {all, fork, take, call, put, takeEvery, takeLatest} from 'redux-saga/effects';
import {
    receivedOrderStatus,
    receiveUserInfo,
    userDidSignIn,
    userDidSignOut,
} from './actions';
import TokenStorage from '../utils/TokenStorage';
import ApiService from '../utils/ApiService';
import * as types from './types';

export function* checkAuthentication() {
    try {
        let accessToken = yield TokenStorage.getToken();
        if (accessToken) {
            yield put(userDidSignIn());
        }
    } catch (e) {
        // yield put(userDidSignOut());
        console.error(e.message);
    }
}

export function* fetchUserInfo() {
    try {
        let response = yield ApiService.get('/auth/user/info');
        yield put(receiveUserInfo(response.data));
    } catch (e) {
        yield put(userDidSignOut());
    }
}

export function* fetchOrderStatus() {
    try {
        let response = yield ApiService.get('/pilot/options/order-status');
        yield put(receivedOrderStatus(response.data));
    } catch (e) {
        console.error(e.message);
    }
}

export function* fetchVariantMaps() {
    try {
        let response = yield ApiService.get('/pilot/options/variant-maps');
        yield put({
            type: types.RECEIVE_VARIANT_MAPS,
            payload: response.data
        });
    } catch (e) {
        console.error(e.message);
    }
}

export function* fetchVariants() {
    try {
        let response = yield ApiService.get('/pilot/options/variants');
        yield put({
            type: types.RECEIVE_VARIANTS,
            payload: response.data
        });
    } catch (e) {
        console.error(e.message);
    }
}

export function* watchUser() {
    yield takeLatest(types.USER_DID_CHANGE, fetchUserInfo);
    yield takeLatest(types.USER_DID_SIGNIN, function* () {
        yield fetchUserInfo();
        yield fetchVariants();
    });
}

export function* sagas() {
    yield all([
        watchUser(),
        checkAuthentication()
    ]);
}
